package test;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultButtonModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

@SuppressWarnings("serial")
public class Example extends JFrame {

	private JLabel statusBar;

	public Example() {
		initUI();
	}

	private static final ImageIcon TICK = new ImageIcon(
			Example.class.getResource("greentick.png"));
	private static final ImageIcon CROSS = new ImageIcon(
			Example.class.getResource("redcross.png"));
	ActionListener EXIT_ACTION = new ActionListener() {
		public void actionPerformed(ActionEvent event) {
			System.exit(0);
		}
	};
	private DefaultListModel model;
	private JList list;
	private JTextPane pane;

	public final void initUI() {

		JMenuBar menubar = new JMenuBar();
		setIconImage(TICK.getImage());
		setLayout(new BorderLayout(2, 2));

		menubar.add(createMenu());

		setJMenuBar(menubar);

		// getContentPane().add(panel);

		// panel.setLayout(null);

		JToolBar toolbar = new JToolBar() {
			{
				add(new JButton("Quit", CROSS) {
					{
						// setBounds(50, 60, 80, 30);
						addActionListener(EXIT_ACTION);
					}
				});
				setFloatable(false);
				setAlignmentX(0);

			}
		};
		JToolBar anotherToolbar = new JToolBar() {
			{
				add(new JButton("Exit", TICK) {
					{
						addActionListener(EXIT_ACTION);
					}
				});
				// setFloatable(false);
				setAlignmentX(0);
			}
		};

		// panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		add(toolbar, BorderLayout.NORTH);

		JTextArea textArea = new JTextArea("Blah blah blha") {
			{
				setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
				setPreferredSize(new Dimension(100, 100));
				addFocusListener(new FocusListener() {

					@Override
					public void focusLost(FocusEvent arg0) {
						statusBar.setBackground(Color.RED);
					}

					@Override
					public void focusGained(FocusEvent arg0) {
						statusBar.setBackground(null);
					}
				});

			}
		};
		JTree tree = new JTree();
		tree.setPreferredSize(new Dimension(100, 100));

		JPanel panel = new JPanel();
		// panel.setLayout(new GridLayout(2, 2));
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

		anotherToolbar.setAlignmentX(1);
		panel.add(anotherToolbar);
		panel.add(Box.createVerticalGlue());
		JPanel bottomPanel = new JPanel();
		bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
		// bottomPanel.setPreferredSize(preferredSize)
		bottomPanel.add(Box.createVerticalStrut(100));

		bottomPanel.add(Box.createRigidArea(new Dimension(20, 20)));
		bottomPanel.add(textArea);
		bottomPanel.add(Box.createRigidArea(new Dimension(50, 50)));
		bottomPanel.add(tree);

		panel.add(bottomPanel);
		JPanel textPanel = new JPanel(new BorderLayout());
		textPanel.setBorder(BorderFactory.createEmptyBorder(15, 25, 15, 25));

		pane = new JTextPane();
		pane.setContentType("text/html");
		String text = "<p><b>Closing windows using the mouse wheel</b></p>"
				+ "<p>Clicking with the mouse wheel on an editor tab closes the window. "
				+ "This method works also with dockable windows or Log window tabs.</p>";
		pane.setText(text);
		// pane.setEditable(false);
		textPanel.add(pane);
		panel.add(textPanel);

		model = new DefaultListModel();
		list = new JList(model);
		list.setPreferredSize(new Dimension(100, 150));
		panel.add(list);

		// panel.setBorder(new EmptyBorder(new Insets(5, 5, 5, 5)));
		add(panel, BorderLayout.CENTER);
		// panel.add(quitButton);

		statusBar = new JLabel(" Statusbar");
		statusBar.setBorder(BorderFactory
				.createEtchedBorder(EtchedBorder.RAISED));
		add(statusBar, BorderLayout.SOUTH);
		setTitle("Simple example");

		final JPopupMenu popupMenu = new JPopupMenu("Label!");
		popupMenu.add(createMenu());

		addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON3) {
					popupMenu.show(Example.this, e.getX(), e.getY());
				}
			}

		});
		// setSize(300, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);

		addComponentListener(new ComponentAdapter() {

			@Override
			public void componentMoved(ComponentEvent e) {
				statusBar.setText("X: " + getX() + ", Y: " + getY());
			}

		});
		pack();
		setLocationRelativeTo(null);
		
		
		JFrame otherStuff = new JFrame(){{
			setResizable(false);
			
//			removeMinMaxClose(this);
			setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
			setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
			add(new JCheckBox("CheckBox!"){{setAlignmentX(0.8f);}});
			add(new JSlider());
			add(new JButton("Model"){{
				addChangeListener(new ChangeListener() {
		            public void stateChanged(ChangeEvent e) {

		            DefaultButtonModel model = (DefaultButtonModel) getModel();
		            
		            String s = "";
		            if (model.isEnabled())
		                s += "Enabled! ";
//		            else
//		                enabled.setText("Enabled: false");

		            if (model.isArmed())
		                s += "Armed! ";
//		            else
//		                armed.setText("Armed: false");

		            if (model.isPressed())
	            		s += "Pressed! ";
//		            	else
//		                pressed.setText("Pressed: false");
		            setEnabled(false);
		            statusBar.setText(s);
		            
		            
		            }
		            
		        });
				
			}});
			add(new JComboBox(UIManager.getInstalledLookAndFeels()) {{
				addActionListener(new ActionListener() {
					
					@Override
					public void actionPerformed(ActionEvent event) {
						try {
							UIManager.setLookAndFeel(((LookAndFeelInfo) getSelectedItem()).getClassName());
							SwingUtilities.updateComponentTreeUI(Example.this);		
							Example.this.pack();
							} catch (ClassNotFoundException e1) {
							e1.printStackTrace();
						} catch (InstantiationException e1) {
							e1.printStackTrace();
						} catch (IllegalAccessException e1) {
							e1.printStackTrace();
						} catch (UnsupportedLookAndFeelException e1) {
							e1.printStackTrace();
						}
					}
				});
				
				
				setRenderer(new ListCellRenderer() {
					@Override
					public Component getListCellRendererComponent(JList list, Object value,
							int index, boolean isSelected, boolean cellHasFocus) {
						String s = null;
						
						if(value instanceof LookAndFeelInfo) {
							s = ((LookAndFeelInfo) value).getName();
						} else {
							s = "" + value;
						}
						return new JLabel(s);
					}
				});
			}});
			
			
			pack();
//			removeMinMaxClose(this);
			
//			setLocationRelativeTo(Example.this);
//			setLocation(Example.this.getX() + Example.this.getWidth(), Example.this.getY());
//			setVisible(true);
			
			
			
		}};
		dockTogether(this, otherStuff);
		
		
		setVisible(true);
		
	}

	public static void main(String[] args) throws ClassNotFoundException,
			InstantiationException, IllegalAccessException,
			UnsupportedLookAndFeelException {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
//		UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");

		
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new Example();
//				ex.setVisible(true);
			}
		});
	}

	private void doListThing(ActionEvent e) {
		Locale locale = Locale.getDefault();
		Date date = new Date(e.getWhen());
		String s = DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(
				date);

		if (!model.isEmpty()) {
			model.clear();
		}

		if (e.getID() == ActionEvent.ACTION_PERFORMED) {
			model.addElement(" Event Id: ACTION_PERFORMED");
		}

		model.addElement(" Time: " + s);
		model.addElement("When: " + e.getWhen());
		model.addElement("What: " + e.getActionCommand());
		String source = e.getSource().getClass().getName();
		model.addElement(" Source: " + source);

		int mod = e.getModifiers();

		StringBuffer buffer = new StringBuffer(" Modifiers: ");

		if ((mod & ActionEvent.ALT_MASK) > 0) {
			buffer.append("Alt ");
		}

		if ((mod & ActionEvent.SHIFT_MASK) > 0) {
			buffer.append("Shift ");
		}

		if ((mod & ActionEvent.META_MASK) > 0) {
			buffer.append("Meta ");
		}

		if ((mod & ActionEvent.CTRL_MASK) > 0) {
			buffer.append("Ctrl ");
		}

		model.addElement(buffer);
		model.addElement(new Integer("1"));
	}

	private JMenu createMenu() {
		return new JMenu("File") {
			{
				setMnemonic(KeyEvent.VK_F);

				JMenuItem eMenuItem = new JMenuItem("Exit", CROSS);
				eMenuItem.setMnemonic(KeyEvent.VK_C);
				eMenuItem.setToolTipText("Exit application");
				eMenuItem.addActionListener(EXIT_ACTION);

				add(eMenuItem);
				add(new JSeparator());
				add(new JMenu("Others") {
					{
						setMnemonic(KeyEvent.VK_O);
						add(new JMenuItem("Thing A", TICK) {
							{
								setMnemonic(KeyEvent.VK_A);
								setToolTipText("Blah!");
								setAccelerator(KeyStroke.getKeyStroke(
										KeyEvent.VK_A, ActionEvent.CTRL_MASK));
								addActionListener(new ActionListener() {

									@Override
									public void actionPerformed(ActionEvent e) {
										doListThing(e);
									}
								});
							}
						});
						add(new JMenuItem("Thing B") {
							{
								setMnemonic(KeyEvent.VK_A);
								setToolTipText("Blah!");
								setAccelerator(KeyStroke.getKeyStroke(
										KeyEvent.VK_B, ActionEvent.CTRL_MASK));
								addActionListener(new ActionListener() {

									@Override
									public void actionPerformed(ActionEvent arg0) {
										// System.out.println("B!");
										JOptionPane.showMessageDialog(
												Example.this,
												"Could not open file", "Error",
												JOptionPane.ERROR_MESSAGE);
									}
								});
							}
						});
						add(new JCheckBoxMenuItem("Tickey") {
							{
								setMnemonic(KeyEvent.VK_T);
								setState(true);

								addActionListener(new ActionListener() {

									@Override
									public void actionPerformed(ActionEvent e) {
										statusBar.setVisible(!statusBar
												.isVisible());
									}
								});
							}
						});
						add(new JMenuItem("Aboot!") {
							{
								setMnemonic(KeyEvent.VK_T);
								setToolTipText("AbooT!");
								setAccelerator(KeyStroke.getKeyStroke(
										KeyEvent.VK_D, ActionEvent.CTRL_MASK));
								addActionListener(new ActionListener() {

									@Override
									public void actionPerformed(ActionEvent arg0) {
										showADialog();
									}
								});
							}
						});
						add(new JMenuItem("Colour!") {
							{
								setMnemonic(KeyEvent.VK_C);
								setToolTipText("Choose a colour!!");
								setAccelerator(KeyStroke.getKeyStroke(
										KeyEvent.VK_C, ActionEvent.CTRL_MASK));
								addActionListener(new ActionListener() {
									@Override
									public void actionPerformed(ActionEvent arg0) {
										Color color = JColorChooser.showDialog(
												Example.this, "Choose Color",
												Color.white);
										pane.setBackground(color);
									}
								});
							}
						});
						add(new JMenuItem("File!") {
							{
								setMnemonic(KeyEvent.VK_F);
								setToolTipText("Choose a file!!");
								setAccelerator(KeyStroke.getKeyStroke(
										KeyEvent.VK_F, ActionEvent.CTRL_MASK));
								addActionListener(new ActionListener() {
									@Override
									public void actionPerformed(ActionEvent arg0) {
										JFileChooser fileopen = new JFileChooser();
										FileFilter filter = new FileNameExtensionFilter(
												"Java files", "java");
										fileopen.addChoosableFileFilter(filter);

										int ret = fileopen.showDialog(
												Example.this, "Open file");

										if (ret == JFileChooser.APPROVE_OPTION) {
											File file = fileopen
													.getSelectedFile();
											try {
												FileReader in = new FileReader(
														file);
												BufferedReader brd = new BufferedReader(
														in);
												StringBuilder sb = new StringBuilder();
												String line = null;
												while ((line = brd.readLine()) != null) {
													sb.append(line)
															.append("<br/>");
												}

												in.close();
												pane.setText(sb.toString());
											} catch (IOException e) {
												System.err.print("Error: " + e);
												return;
											}
										}
									}
								});
							}
						});

					}
				});
			}
		};
	}

	private void showADialog() {
		JDialog dialog = new JDialog() {
			{
				setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

				add(Box.createRigidArea(new Dimension(0, 10)));

				ImageIcon icon = TICK;
				JLabel label = new JLabel(icon);
				label.setAlignmentX(0.5f);
				add(label);

				add(Box.createRigidArea(new Dimension(0, 10)));

				JLabel name = new JLabel("Notes, 1.23");
				name.setFont(new Font("Serif", Font.BOLD, 13));
				name.setAlignmentX(0.5f);
				add(name);

				add(Box.createRigidArea(new Dimension(0, 50)));

				JButton close = new JButton("Close");
				close.addActionListener(new ActionListener() {

					public void actionPerformed(ActionEvent event) {
						dispose();
					}
				});

				close.setAlignmentX(0.5f);
				add(close);

				setModalityType(ModalityType.APPLICATION_MODAL);

				setTitle("About Notes");
				setDefaultCloseOperation(DISPOSE_ON_CLOSE);
				setLocationRelativeTo(null);
				setSize(300, 200);

			}
		};
		dialog.setVisible(true);

	}

	
	public static void dockTogether(final Window parent, final Window child) {
		child.setLocationRelativeTo(parent);
		
		parent.addComponentListener(new ComponentAdapter() {

			@Override
			public void componentHidden(ComponentEvent e) {
				child.setVisible(false);
			}

			@Override
			public void componentMoved(ComponentEvent e) {
				moveWith();
			}

			@Override
			public void componentResized(ComponentEvent e) {
				moveWith();
			}

			@Override
			public void componentShown(ComponentEvent e) {
				child.setVisible(true);
			}
			 private void moveWith() {
				 child.setLocation(parent.getX() + parent.getWidth(), parent.getY());
				 
			 }
			
		});
		
		
	}
	public void removeMinMaxClose(Component comp)   
	{   
	  if(comp instanceof JButton)   
	  {   
	    String accName = ((JButton) comp).getAccessibleContext().getAccessibleName();   
	    System.out.println(accName);   
//	    if(accName.equals("Maximize")|| accName.equals("Iconify")||   
//	       accName.equals("Close")) 
	    	comp.getParent().remove(comp);   
	  }   
	  if (comp instanceof Container)   
	  {   
	    Component[] comps = ((Container)comp).getComponents();   
	    for(int x = 0, y = comps.length; x < y; x++)   
	    {   
	      System.out.println(comps[x].getName() + ": " + comps[x].getAccessibleContext().getAccessibleName() + ": " + comps[x].getClass());
	    	
	    	
	    	
	    	removeMinMaxClose(comps[x]);   
	    }   
	  }   
	}   	
//	  public void removeMinMaxClose(Component comp)  
//	  {  
//	    if(comp instanceof AbstractButton)  
//	    {  
//	    	System.out.println("button");
//	      comp.getParent().remove(comp);  
//	    }  
//	    if (comp instanceof Container)  
//	    {  
//	    	System.out.println("container");
//	      Component[] comps = ((Container)comp).getComponents();  
//	      for(int x = 0, y = comps.length; x < y; x++)  
//	      {  
//		    	System.out.println("component");
//	        removeMinMaxClose(comps[x]);  
//	      }  
//	    }  
//	  }  

}